<template>
  <div>
    <newHeader></newHeader>
    <swiperComponent></swiperComponent>
    <div class="m-content wrapbox clearfix">
      <div class="m-leftbar">
        <div v-bind:class="{ 'm-hotset': true, 'm-hotset-more': tagsIsActive}">
          <h2 class="sider-title">热门标签</h2>
          <div class="box">
            <ul class="clearfix">
              <li v-for="item in categoryCategory">
                <a v-on:click="clickTag(1,item)" v-bind:class="{ 'selectTag': item.code ==category}"> {{ item.name
                  }}</a>
              </li>
            </ul>

            <ul class="clearfix">
              <li v-for="item in categoryCurrency">
                <a v-on:click="clickTag(2,item)" v-bind:class="{ 'selectTag': item.code ==currency}"> {{ item.name
                  }}</a>
              </li>
            </ul>
            <ul class="clearfix">
              <li v-for="item in categoryCountry">
                <a v-on:click="clickTag(3,item)" v-bind:class="{ 'selectTag': item.code ==country}"> {{ item.name }}</a>
              </li>
            </ul>
            <ul class="clearfix">
              <li v-for="item in categoryLanguage">
                <a v-on:click="clickTag(4,item)" v-bind:class="{ 'selectTag': item.code ==language}"> {{ item.name
                  }}</a>
              </li>
            </ul>
          </div>

          <!-- 展开状态添加 class arr-up -->
          <a v-on:click="tagsIsActive=!tagsIsActive" class="arr"><span></span></a>
        </div>

        <div class="articles" v-if="articles && articles.length">
          <ul>
            <li class="article-item" v-for="(article, index) in articles" :key="index">
              <article-block
                :article="article"
                :tags="article.tags || []"
                :comments="article.comments || []"
                @load-comments="loadMoreComment(article)"
                @share="onShare(article)"
                @like="onLike"
                @post-comment="onPostComment"
                @like-comment="onLikeComment"
                @report-comment="onReportComment"
                @delete-comment="onDeleteComment"
                @post-comment-reply="onPostCommentReply"
                @report-reply="onReportReply"
                @post-reply-reply="onPostReplyReply"
                @delete-reply="onDeleteReply">
              </article-block>
            </li>
          </ul>
        </div>
        <vue-paginate-al :nextText="paginate.nextText" :prevText="paginate.prevText" :totalPage="totalPage"
                         :currentPage="currentPage" @btnClick="getNews"></vue-paginate-al>
      </div>
      <div class="m-rightbar">
        <!-- S 侧边栏 -->
        <div class="n-sider">
          <h2 class="sider-title">头条资讯</h2>
          <ul class="n-img-list">
            <li v-for="(item,index) in topLines">
              <router-link v-bind="{to:'/newDetail/'+ item.id}">
                <i>{{index+1}}</i>
                <img :src="item.picUrl"/>
                <h5>{{item.newsTitle}}</h5>
                <p>{{item.newsAbstract}}</p>
              </router-link>
            </li>
          </ul>
          <h2 class="sider-title sider-title2">干货</h2>
          <ul class="n-list">
            <li v-for="item in driedStuff">
              <router-link v-bind="{to:'/newDetail/'+ item.id}">
                <h5>{{item.newsTitle}}</h5>
                <p>{{item.newsAbstract}}</p>
              </router-link>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <bottom></bottom>
  </div>
</template>

<script>
  import newHeader from '@/components/NewHeader';
  import bottom from '@/components/Bottom';
  import swiperComponent from '@/components/SSwiper';
  import articleBlock from '@/components/article-block/index';
  import {mapGetters} from 'vuex'
  import VuePaginateAl from 'vue-paginate-al'

  let STATUS = {
    notStart: '',
    doing: 'doing',
    done: 'done',
    fail: 'fail'
  };

  export default {
    components: {
      bottom,
      newHeader,
      swiperComponent,
      articleBlock,
      VuePaginateAl,
    },
    data() {
      return {
        articles: null,
        currency: '',
        category: '',
        country: '',
        language: '',
        currentPage: 1,
        totalPage: 0,
        categoryCategory: [],
        categoryCurrency: [],
        categoryCountry: [],
        categoryLanguage: [],
        tagsIsActive: false,
        paginate: {
          nextText: '下一页',
          prevText: '上一页',

        },
        topLines: [],
        driedStuff: [],
      };
    },
    mounted() {

      this.getNewsList()
      this.getTags()
      this.getTopLine()
      this.getDriedStuffList()
      this.$store.dispatch('updateHeadStatu', false)
    },

    computed: {
      ...mapGetters({
        userId: 'userId',
        username: 'username',
        photo: 'photo',
      })
    },
    methods: {
      getTopLine() {
        this.$fetch('/indexNews/getHeadlineNewsList').then(response => {
          this.$check(response)
          this.topLines = response.data
        })
      },
      //获取干货
      getDriedStuffList() {
        this.$fetch('/indexNews/getDriedStuffList').then(response => {
          this.$check(response)
          this.driedStuff = response.data
        })
      },
      getNews(n) {
        this.currentPage = n
        this.getNewsList()

      },
      getTags() {
        this.$fetch('/indexNews/getBcHotTagList').then(response => {
          this.$check(response)
          let tags = response.data
          if (tags.length != 0) {
            tags.forEach(function (v) {
              if (v.category == 'category') {
                this.categoryCategory.push(v)
              }
              if (v.category == 'currency') {
                this.categoryCurrency.push(v)
              }
              if (v.category == 'country') {
                this.categoryCountry.push(v)
              }
              if (v.category == 'language') {
                this.categoryLanguage.push(v)
              }
            }, this)
          }
        })
      },
      onShare(article) {
        this.$post('/indexNews/addNewsShares', {
          "newsId": article.id
        }).then(response => {
          this.$check(response)
          article.shareCount += 1;
        })
      },
      onLike(article, status) {
        article.likeActionStatus = STATUS.doing;
        // TODO send like request
        for (let item of this.articles) {
          if (item.id === article.id) {
            let likeInd = 1
            if (item.likeDone) {
              likeInd = 3
            } else {
              likeInd = 1
            }
            this.$post('/indexNews/addNewsLikesOrDislikes', {
              'id': article.id,
              'likeInd': likeInd,
              'type': 1
            }).then(response => {
              this.$check(response)
              item.likeDone = !article.likeDone;
              if (item.likeDone) {
                item.likeCount += 1;
              } else {
                item.likeCount -= 1;
              }
              this.$message.success('操作成功');
              item.likeActionStatus = STATUS.done;

            })
            break;
          }
        }
      },
      onLikeComment(comment, status) {
        comment.likeActionStatus = STATUS.doing;
        // TODO send like request
        let likeInd = 1
        if (comment.likeDone) {
          likeInd = 3
        } else {
          likeInd = 1
        }
        this.$post('/indexNews/addNewsLikesOrDislikes', {
          'id': comment.id,
          'likeInd': likeInd,
          'type': 2
        }).then(response => {
          this.$check(response)
          comment.likeDone = !comment.likeDone;
          if (comment.likeDone) {
            comment.likeCount += 1;
          } else {
            comment.likeCount -= 1;
          }
          this.$message.success('操作成功');
          comment.likeActionStatus = STATUS.done;
        })

      },
      //提交评论
      onPostComment(article, comment) {
        article.postActionStatus = STATUS.doing;
        let params = {
          'newsId': article.id,
          'content': comment,
          'parentId': 0,
          'commentType': article.commentType,
          'newsType': 0
        }
        this.$post('/indexNews/addNewsComment', params).then(response => {
          this.$check(response)
          article.comments.unshift({
            user: {
              avatar: this.photo,
              nickname: this.username
            },
            id: response.data,
            text: comment,
            likeDone: false,
            likeCount: 0,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: true,
            replies: []
          });
          article.messageCount += 1;
          article.postActionStatus = STATUS.done;
        })
      },
      onReportComment(comment, reportArgs,article) {
        comment.reportActionStatus = STATUS.doing
        this.$post('/indexNews/newsCommentTips', {
          'commentId': comment.id,
          'content': reportArgs.text,
          'type': reportArgs.value
        }).then(response => {
          this.$check(response)
          this.$message.success('举报成功');
          comment.reportActionStatus = STATUS.done
        })
      },
      onDeleteComment(article, comment) {
        let commentFound = false;
        let count = 0;
        for (let item of article.comments) {
          if (item.id === comment.id) {
            commentFound = true;
            break;
          }
          count += 1;
        }
        if (commentFound) {

          this.$post('/indexNews/delNewsComment', {
            commentId: comment.id,
            newsType: 0
          }).then(response => {
            this.$check(response)
            this.$message.success('删除评论成功');
            article.messageCount -= (1 + comment.replies.length);
            article.comments.splice(count, 1);
          })
        }
      },
      onPostCommentReply(article, comment, reply) {
        comment.postActionStatus = STATUS.doing;
        let params = {
          'newsId': article.id,
          'content': reply,
          'parentId': comment.id,
          'commentType': article.commentType,
          // 'newsType': 0
        }
        this.$post('/indexNews/addNewsComment', params).then(response => {
          this.$check(response)
          comment.replies.unshift({
            user: {
              avatar: this.photo,
              nickname: this.username
            },
            id: response.data,
            text: reply,
            likeDone: false,
            likeCount: 0,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: true,
            replies: []
          });
          comment.postActionStatus = STATUS.done;
          article.messageCount += 1;
        })
      },
      onReportReply(reply, reportArgs,article) {
        reply.reportActionStatus = STATUS.doing
        this.$post('/indexNews/newsCommentTips', {
          'commentId': reply.id,
          'content': reportArgs.text,
          'type': reportArgs.value
        }).then(response => {
          this.$check(response)
          this.$message.success('举报成功');
          reply.reportActionStatus = STATUS.done
        })
      },
      onDeleteReply(article, comment, reply) {
        let replyFound = false;
        let count = 0;
        for (let item of comment.replies) {
          if (item.id === reply.id) {
            replyFound = true;
            break;
          }
          count += 1;
        }
        if (replyFound) {
          this.$post('/indexNews/delNewsComment', {
            commentId: reply.id,
            newsType: 0
          }).then(response => {
            this.$check(response)
            this.$message.success('删除评论成功');
            article.messageCount -= 1;
            comment.replies.splice(count, 1);
          })
        }
      },
      onPostReplyReply(article, comment, reply, content) {
        reply.postActionStatus = STATUS.doing;
        setTimeout(() => {
          comment.replies.unshift({
            user: {
              avatar: 'https://tse1-mm.cn.bing.net/th?id=OIP.9j7o71IyzF7R6d7aTa4iIgHaHa&w=196&h=196&c=7&o=5&pid=1.7',
              nickname: 'jack'
            },
            id: [comment.id, 'rid', comment.replies.length].join('_') + Date.now(),
            text: content,
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: true,
            replyTo: reply
          });
          reply.postActionStatus = STATUS.done;
          article.messageCount += 1;
        }, 1000);
      },
      loadMoreComment(article) {
        // TODO send load comment request, setTimeout 只是为了模拟请求耗时

        let uuid = this.userId
        article.loadActionStatus = STATUS.doing;

        this.$post('/indexNews/getNewsCommentList', {
          condition: {
            'newsId': article.id,
            'userId': uuid,
            'commentType': article.commentType
          },
          current: article.nextCommentPage,
          size: 5
        }).then(response => {
          this.$check(response)
          if (response.data != null) {
            let records = response.data.records

            for (var i = 0; i < records.length; i++) {

              let subComments = this.getComment(records[i].children, uuid)
              article.comments.push({
                user: {
                  avatar: records[i].businessData.photo,
                  nickname: records[i].businessData.nickName,
                },
                id: records[i].businessData.id,
                text: records[i].businessData.contentStr,
                likeDone: records[i].businessData.likeInd == 1,
                likeCount: records[i].businessData.likes,
                likeActionStatus: '',
                postActionStatus: '',
                reportActionStatus: '',
                deleteActionStatus: '',
                canDelete: records[i].businessData.userId = uuid,
                replies: subComments
              })
            }
            if (response.data.records.length == 5) {
              article.nextCommentPage += 1;
            } else {
              article.nextCommentPage = 0;
            }
          } else {
            article.nextCommentPage = 0;
          }
          article.loadActionStatus = STATUS.done;
        })
      }, getComment(records, uuid) {
        let list = []
        for (var i = 0; i < records.length; i++) {
          list.push({
            user: {
              avatar: records[i].businessData.photo,
              nickname: records[i].businessData.nickName,
            },
            id: records[i].businessData.id,
            text: records[i].businessData.contentStr,
            likeDone: records[i].businessData.likeInd == 1,
            likeCount: records[i].businessData.likes,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: records[i].businessData.userId = uuid,
            replies: []
          })
        }
        // console.log(list)
        return list
      },


      getNewsList() {
        let params = {
          'condition': {
            'userId': this.userId,
            'currency': this.currency,
            'category': this.category,
            'country': this.country,
            'language': this.language,
          },
          'current': this.currentPage,
          'pages': this.totalPage,
          'size': 10,
          'total': 0

        }
        this.$post('/indexNews/getNewsList', params).then(response => {
          this.$check(response)
          this.articles = this.transfer(response.data.records)
          this.currentPage = response.data.current
          this.totalPage = response.data.pages
        })

      },
      transfer(records) {
        let url = this.websideUrl
        records.forEach(function (v) {
          v.title = v.newsTitle
          v.time = v.infopubldate
          v.text = v.newsAbstract
          v.tags = v.tagList
          v.likeDone = v.likeInd == 1
          v.likeCount = v.likes
          v.messageCount = v.comments
          v.shareCount = v.shares
          v.comments = []
          v.likeActionStatus = ''
          v.postActionStatus = ''
          v.loadActionStatus = ''
          v.shareUrl = url + 'newDetail/' + v.id
          v.routerUrl = '/newDetail/' + v.id
          v.nextCommentPage = 1
          v.collectStatus=false
          v.transmitStatus=false
        })
        return records

      }, clickTag(type, item) {
        this.currentPage = 1
        switch (type) {
          case 1:
            if (this.category == item.code) {
              this.category = ''
            } else {
              this.category = item.code
            }
            this.getNewsList()
            break;
          case 2:
            if (this.currency == item.code) {
              this.currency = ''
            } else {
              this.currency = item.code
            }
            this.getNewsList()
            break;
          case 3:
            if (this.country == item.code) {
              this.country = ''
            } else {
              this.country = item.code
            }
            this.getNewsList()
            break;
          case 4:
            if (this.language == item.code) {
              this.language = ''
            } else {
              this.language = item.code
            }
            this.getNewsList()
            break;

        }
      },
    },

    created() {
      // this.getNewsList()
      // let data = require('../../testData/articles');
      // this.articles = data.default;
    }
  };
</script>

<style scoped>
  .article-item {
    padding-bottom: 30px;
    border-bottom: 1px solid #ccc;
    margin-bottom: 15px;
  }

  .selectTag {
    background: #59B3E2;
    color: #fff;
  }

  .article-item:last-child {
    border-bottom: 0 none;
  }
</style>
